jQuery(document).ready(function($) {
	// Error variable
	var bandit_form_error;

	// Fade settings-error div
	if($('.settings-error').length) {
		$('.settings-error').delay(2000).fadeOut('slow');
	}

	// Handle click
	$('.handlediv').click(function() {
		$(this).parent().find('.inside').slideToggle();
	});

	// Check for slider input
	$('#bandit-slider-submit').click(function() {
		// Clear errors
		$('.bandit-slider-new input').removeClass('error');
		bandit_form_error = false;
		// Get field values
		var name = $('.bandit-slider-new input[name="bandit_slider[name]"]');
		// Check Name
		if(name.val() == '') {
			name.addClass('error');
			bandit_form_error = true;
		}
		// Exit if error
		if(bandit_form_error) { return false; }
	});

	// Check for item input
	$('#bandit-item-image-submit').click(function() {
		// Clear errors
		$('.bandit-slider-add-image input').removeClass('error');
		bandit_form_error = false;
		// Get field values
		var image = $('.bandit-slider-add-image input[name="bandit_slider[image]"]');
		// Check Name
		if(image.val() == '') {
			image.addClass('error');
			bandit_form_error = true;
		}
		// Exit if error
		if(bandit_form_error) { return false; }
	});

	// Add Images To Field via Media Library
	if($('.bandit-slider-add-image').length) {
		// Slider Item Image Field
		var slider_item_image_field = $('.bandit-slider-add-image input[name="bandit_slider[image]"]');

		// Set image field; Show media library
		$('.bandit-item-select-image').click(function() {
			tb_show('','media-upload.php?type=image&TB_iframe=true');
			return false;
		});

		// Populate image field with URL; Remove media library
		window.send_to_editor = function(html) {
			var image_url = $('img',html).attr('src');
			slider_item_image_field.val(image_url);
			tb_remove();
		}
	}

	// Delete slider
	$('a.bandit-slider-delete-link').click(function() {
		if( confirm('Are you sure you want to delete this slider?')) {
			$('#bandit-slider-delete').submit();
		}
	});

	// Sortable slider items
	$('.sortable').sortable({
		handle: 'a.bandit-link-move',
		helper: function(e, tr) {
			var originals = tr.children();
			var helper = tr.clone();
			helper.children().each(function(index) {
		  		// Set helper cell sizes to match the original sizes
		  		$(this).width(originals.eq(index).width() + 15)
			});
			return helper;
		}
	});

	// Remove link
	$('a.bandit-link-delete').click(function(){
		if( confirm('Are you sure you want to remove this item?')) {
			var tr = $(this).parent().parent('tr');
			tr.remove();
			return false;
		}
	});

});